const vscode = require('vscode');
const fs = require('fs');
const path = require('path');

class ProjectAnalyzer {
    constructor() {
        this.projectRoot = '';
        this.fileStructure = {};
        this.codeFiles = new Set();
    }

    async initialize(workspaceRoot) {
        this.projectRoot = workspaceRoot;
        await this.analyzeProjectStructure();
    }

    async analyzeProjectStructure() {
        try {
            this.fileStructure = await this.scanDirectory(this.projectRoot);
        } catch (error) {
            console.error('Error analyzing project structure:', error);
        }
    }

    async scanDirectory(dirPath) {
        const structure = {};
        const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });

        for (const entry of entries) {
            const fullPath = path.join(dirPath, entry.name);
            
            if (entry.isDirectory()) {
                if (!this.shouldIgnoreDirectory(entry.name)) {
                    structure[entry.name] = await this.scanDirectory(fullPath);
                }
            } else {
                if (this.isCodeFile(entry.name)) {
                    this.codeFiles.add(fullPath);
                    structure[entry.name] = 'file'; // 仅标记为文件
                }
            }
        }

        return structure;
    }

    shouldIgnoreDirectory(dirName) {
        const ignoreDirs = ['.git', 'node_modules', '.vscode', 'dist', 'build'];
        return ignoreDirs.includes(dirName);
    }

    isCodeFile(fileName) {
        const codeExtensions = ['.js', '.ts', '.jsx', '.tsx', '.html', '.css', '.json', '.vue', '.py'];
        return codeExtensions.some(ext => fileName.endsWith(ext));
    }

    async analyzeFile(filePath) {
        try {
            const content = await fs.promises.readFile(filePath, 'utf8');
            return {
                path: filePath,
                content
            };
        } catch (error) {
            console.error(`Error analyzing file ${filePath}:`, error);
            return null;
        }
    }

    async getProjectState() {
        return {
            structure: this.fileStructure,
            files: await Promise.all(Array.from(this.codeFiles).map(filePath => this.analyzeFile(filePath)))
        };
    }
}

module.exports = ProjectAnalyzer;